var auths = {};

function initAuth() {
    plus.oauth.getServices(function(services) {
        for (var i in services) {
            var service = services[i];
            auths[service.id] = service;
        }
    }, function(e) {
        console.log("获取登录认证失败：" + e.message);
        plus.nativeUI.alert("获取登录认证失败：" + e.message, null, "登录");
    });
}
/**
 * 获取本地是否安装客户端
 **/
function isInstalled(id) {
    if (mui.os.android) {
        var main = plus.android.runtimeMainActivity();
        var packageManager = main.getPackageManager();
        var PackageManager = plus.android.importClass(packageManager)
        var packageName = {
            "qq": "com.tencent.mobileqq",
            "weixin": "com.tencent.mm",
            "sinaweibo": "com.sina.weibo"
        }
        try {
            return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
        } catch (e) {}
    } else {
        switch (id) {
            case "qq":
                var TencentOAuth = plus.ios.import("TencentOAuth");
                return TencentOAuth.iphoneQQInstalled();
            case "weixin":
                var WXApi = plus.ios.import("WXApi");
                return WXApi.isWXAppInstalled()
            case "sinaweibo":
                var SinaAPI = plus.ios.import("WeiboSDK");
                return SinaAPI.isWeiboAppInstalled()
            default:
                break;
        }
    }
}

function loginApp(id) {
    var auth = auths[id];
    if (auth) {
        var w = null;
        if (plus.os.name == "Android") {
            w = plus.nativeUI.showWaiting();
        }
        document.addEventListener("pause", function() {
            setTimeout(function() {
                w && w.close();
                w = null;
            }, 2000);
        }, false);
        auth.login(function() {
            w && w.close();
            w = null;
            getUserinfo(auth);
        }, function(e) {
            w && w.close();
            w = null;
            plus.nativeUI.alert("登录认证失败", null, "登录");
            //plus.nativeUI.alert("详情错误信息请参考授权登录(OAuth)规范文档：http://www.html5plus.org/#specification#/specification/OAuth.html",null,"登录失败["+e.code+"]："+e.message);
        });
    } else {
        plus.nativeUI.alert("请先安装App！", null, "登录");
    }
}
// 获取用户信息
function getUserinfo(a) {
    a.getUserInfo(function() {
            // outLine("获取用户信息成功：");
            // outLine(JSON.stringify(a.userInfo));
            var nickname = a.userInfo.nickname || a.userInfo.name || a.userInfo.miliaoNick;
            console.log("userinfo:", JSON.stringify(a.userInfo));
            app.$store.commit({ type: "loginApp", "userinfo": a.userInfo });
            // plus.nativeUI.alert("欢迎“" + nickname + "”登录！");
        },
        function(e) {
            // outLine("获取用户信息失败：");
            // outLine("[" + e.code + "]：" + e.message);
            plus.nativeUI.alert("获取用户信息失败！", null, "登录");
        });
}